import csv


def read_csv(csv_name):
    f = open(csv_name, 'r')
    reader = csv.reader(f)
    result = []
    for row in reader:
        row = [float(s) for s in row]
        result.append(row)
    return result

def write_result(result):
    f = open('data_devide_result.csv', 'w', encoding='utf-8', newline='')
    csv_writer = csv.writer(f)
    for res in result:
        csv_writer.writerow(res)
    f.close()

# 数据划分
def data_devide(input_example):
    pca_result=read_csv(input_example)
    pca_result_0 = [pca_result]
    for i in range(8):
        locals()['pca_result_'+str(i+1)] = []
        for pca in locals()['pca_result_'+str(i)]:
            pca_sorted=sorted(pca, key=lambda x: x[i + 1], reverse=True)
            pca_result_xy=devide(pca_sorted)
            for pca_xy in pca_result_xy:
                locals()['pca_result_'+str(i+1)].append(pca_xy)
    write_result(locals()['pca_result_'+str(i+1)])
    return locals()['pca_result_'+str(i+1)]

def devide(pca_result):
    length=len(pca_result)
    pca_result_x=pca_result[:(length//2)]
    pca_result_y=pca_result[(length//2):]
    pca_result_xy=[]
    pca_result_xy.append(pca_result_x)
    pca_result_xy.append(pca_result_y)
    return  pca_result_xy


def read_csv_plus(csv_name):
    f = open(csv_name, 'r')
    reader = csv.reader(f)
    result = []
    for row in reader:
        res=[]
        for re in row:
            re=re[1:-1].split(', ')
            re= [float(s) for s in re]
            res.append(re)
        result.append(res)
    return result


input_example = 'data_reduction.csv'
output_example = 'data_devide_example.csv'
output = data_devide(input_example)



def compare(o_e, o):
    #修改比较方式
    result_example = read_csv_plus(o_e)
    result = o
    if (result_example == result):
        return True
    else:
        return False

print("")

# 用例目的
print("该用例目的为：对数据降维后的数据进行数据划分，以便下一步的数据聚合")

print("")

# 子用例编号
print("子用例编号：data_devide_1")

print("")

print("****************************")
print("当前输入为：")
print(input_example)

print("")
print("****************************")
print("当前输出格式为:")
print([len(output),len(output[0]),len(output[0][0])])

print("****************************")
print("由于数据量过大，展示输出中的第一组数据中的第一个数据:")
print(output[0][0])
print("")
print("****************************")
print("预设输出格式为:")




print([len(read_csv_plus(output_example)),len(read_csv_plus(output_example)[0]),len(read_csv_plus(output_example)[0][0])])

print("****************************")
print("由于数据量过大，展示预设输出中的第一组数据的第一个数据:")
# 输出处理后数据
print(read_csv_plus(output_example)[0][0])
print("")

print("****************************")
print("是否正确:")
# 输出对比结果
# 需要写一个compare函数
if compare(output_example, output):
    print("输出与预定目标相符")
else:
    print("输出与预定目标不符")
# 输出对比结果

print("\n")
